﻿<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="listQuery.name"
        placeholder="名称"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <el-button
        v-waves
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleFilter"
      >搜索</el-button>
      <el-button
        v-if="isPreview === false"
        class="filter-item"
        type="primary"
        icon="el-icon-plus"
        @click="handleCreate"
      >
        添加
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      style="width: 100%"
      :data="list"
      @sort-change="sortChange"
    >
      <el-table-column label="字典名称" width="110px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.dictName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="序号" width="110px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.sortNumber }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" width="110px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.remark }}</span>
        </template>
      </el-table-column>
      <el-table-column
        v-if="isPreview === false"
        label="操作"
        align="center"
        width="230"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="{row}">
          <el-button type="primary" size="mini" icon="el-icon-edit" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button size="mini" type="danger" icon="el-icon-delete" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="35%">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="right"
        label-width="100px"
        style="width: 350px; margin-left:50px;"
      >
        <el-form-item label="字典名称" prop="dictName">
          <el-input v-model="temp.dictName" />
        </el-form-item>
        <el-form-item label="序号:" prop="sortNumber">
          <el-input-number v-model="temp.sortNumber" class="custom-width" :min="0" :max="100" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="temp.remark" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button :loading="loading" type="primary" @click="dialogStatus==='create'?createData():updateData()">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import waves from '@/directive/waves'
import { parseTime, uuid } from '@/utils'
import Pagination from '@/components/Pagination'

export default {
  name: 'SysDictionaryData',
  components: { Pagination },
  directives: { waves },
  props: {
    details: {
      type: Array,
      required: true
    },
    isPreview: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      tableKey: 0,
      total: 0,
      list: [],
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 10,
        name: undefined,
        sorting: 'creationTime'
      },
      dialogFormVisible: false,
      downloadLoading: false,
      textMap: {
        update: '编辑字典数据',
        create: '添加字典数据'
      },
      temp: {
        id: '',
        sysDictionaryId: '',
        dictName: '',
        sortNumber: 0,
        remark: ''
      },
      rules: {
        dictName: [{ required: true, message: '字典名称必须填写', trigger: 'blur' }],
        sortNumber: [{ required: true, message: '序号必须填写', trigger: 'blur' }]
      },
      dialogStatus: '',
      loading: false
    }
  },
  watch: {
    details(newValue) {
      this.total = newValue.length
      this.getList()
    }
  },
  methods: {
    getList() {
      this.listLoading = true

      const start = (this.listQuery.page - 1) * this.listQuery.limit

      const end = this.listQuery.page * this.listQuery.limit

      if (this.listQuery.name) {
        const listFilter = this.details.filter(f => f.dictName.includes(this.listQuery.name))
        this.list = listFilter.slice(start, end)
      } else {
        this.list = this.details.slice(start, end)
      }

      this.listLoading = false
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'creationTime') {
        this.sortByCreationTime(order)
      }
    },
    sortByCreationTime(order) {
      if (order === 'ascending') {
        this.listQuery.sorting = 'creationTime'
      } else {
        this.listQuery.sorting = 'creationTime desc'
      }
      this.handleFilter()
    },
    handleDelete(row) {
      this.$confirm('此操作将删除该, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(() => {
        const { id } = row
        this.deleteDetail(id)
      }).catch(() => {
      })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['timestamp', 'title', 'type', 'importance', 'status']
        const filterVal = ['timestamp', 'title', 'type', 'importance', 'status']
        const data = this.formatJson(filterVal, this.list)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'table-list'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}`
        ? 'ascending'
        : sort === `-${key}`
          ? 'descending'
          : ''
    },
    addDetail(data) {
      this.$emit('addDetail', data)
    },
    updateDetail(data) {
      this.$emit('updateDetail', data)
    },
    deleteDetail(id) {
      this.$emit('deleteDetail', id)
    },
    createData() {
      this.dialogFormVisible = false
      this.addDetail(this.temp)
    },
    updateData() {
      this.dialogFormVisible = false
      this.updateDetail(this.temp)
    },
    resetTemp() {
      this.temp = {
        dictCode: '',
        dictName: '',
        sortNumber: 0,
        remark: ''
      }
    },
    handleCreate() {
      this.resetTemp()
      this.temp.id = uuid()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleUpdate(row) {
      this.temp = { ...row }
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
    }
  }
}
</script>

<style lang="scss" scoped>
.custom-width {
  width: 100%;
}
</style>
